<?php

namespace Tools\Encryption;

/**
 * Rsa加密
 * @author kqhenbang
 */
class RsaTool
{
    /**
     * 真实公钥
     * @param string $publicKey
     * @return string
     */
    public static function realPublicKey(string $publicKey): string
    {
        $publicKey = urldecode($publicKey);
        $publicKey = ltrim($publicKey,'BEGIN');
        $publicKey = '-----BEGIN PUBLIC KEY-----'.$publicKey;
        $publicKey = rtrim($publicKey,'END');
        $publicKey = $publicKey.'-----END PUBLIC KEY-----';
        $publicKey = explode(PHP_EOL, $publicKey);
        unset($publicKey[2]);
        $publicKey = implode('\r\n',$publicKey);
        return str_replace('\r\n', PHP_EOL, $publicKey);
    }

    /**
     * 私钥加密
     * @param $data
     * @param string $privateKey
     * @return string
     */
    public static function privateEncrypt($data, string $privateKey): string
    {
        openssl_private_encrypt($data, $encrypted, $privateKey);
        return base64_encode($encrypted);
    }

    /**
     * 私钥解密
     * @param $encrypted
     * @param string $privateKey
     * @return mixed
     */
    public static function privateDecrypt($encrypted, string $privateKey)
    {
        openssl_private_decrypt(base64_decode($encrypted), $decrypted,$privateKey);
        return $decrypted;
    }

    /**
     * 公钥加密
     * @param string $data
     * @param string $publicKey
     * @return string|false
     */
    public static function publicEncrypt(string $data, string $publicKey)
    {
        if (openssl_public_encrypt($data, $encrypted, $publicKey)) {
            $encrypted = base64_encode($encrypted);
        } else { // 可能加密字符串太长
            return false;
        }
        return $encrypted;
    }

    /**
     * 公钥解密
     * @param string $encrypted
     * @param string $publicKey
     * @return mixed
     */
    public static function publicDecrypt(string $encrypted, string $publicKey)
    {
        openssl_public_decrypt(base64_decode($encrypted), $decrypted, $publicKey);
        return $decrypted;
    }
}